<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示警告区域 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs 页 导航 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" type="number" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" type="number" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyDataList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="val"
                  v-for="(val, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyDataList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button class="addBtn" type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片对话框 -->
    <el-dialog title="预览图片" :visible.sync="previewVisible" width="30%">
      <img class="previewImg" :src="previewPath" alt="">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 绑定 tabs页切换
      activeIndex: "0",
      // 添加商品表单数据
      addForm: {
        goods_name: "",
        goods_price: null,
        goods_weight: null,
        goods_number: null,
        // 级联选择器双向绑定数据
        goods_cat: [],
        // 图片临时路径
        pics: [],
        // 介绍
        goods_introduce: "",
        attrs: []
      },
      // 添加商品表单验证
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格名称", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 分类列表数据
      cateList: [],
      // 级联选择器的配置信息
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      // 动态参数数据列表
      manyDataList: [],
      // 静态属性数据列表
      onlyDataList: [],
      // 图片上传地址
      uploadURl: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片上传请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片对话框的展示与隐藏
      previewVisible: false,
      // 预览图片地址
      previewPath: ''
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取分类列表
    async getCateList() {
      let { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类列表失败！");
      }
      this.cateList = res.data;
    },

    // 级联选择器的 change 监听
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },

    // 在 tab标签页切换之前监听是否完成校验
    beforeTabLeave() {
      //
      let status = false;
      // 预验证表单是否都填写才跳转到下一标签页
      this.$refs.addFormRef.validate((vali) => {
        if (!vali) {
          this.$message.error("请填写相关信息！");
          status = false;
        } else {
          status = true;
        }
      });
      return status;
    },

    // 点击切换tab标签页时请求不同参数
    async tabClicked() {
      if (this.activeIndex === "1") {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数失败！");
        }
        // 循环数据把 参数 遍历出来添加到 manyDataList
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
        this.manyDataList = res.data;
      } else if (this.activeIndex === "2") {
        let { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取参数失败！");
        }
        this.onlyDataList = res.data;
      }
    },

    // 预览成功上传的图片
    handlePreview(file) {
      // 获取预览图片的完整地址
      this.previewPath = file.response.data.url;
      // 展示对话框
      this.previewVisible = true
    },

    // 监听图片被移除触发
    handleRemove(file) {
      // 获取被删除的图片路径
      let pic = file.response.data.tmp_path;
      // 去数组中遍历找出匹配的索引项
      let index = this.addForm.pics.findIndex((item) => {
        return item.pic === pic;
      });
      // 根据获取到的索引去删除数组的项
      this.addForm.pics.splice(index, 1);
    },

    // 图片上传成功后触发
    handleSuccess(response) {
      let pics = {
        pic: response.data.tmp_path,
      };
      this.addForm.pics.push(pics);
    },

    // 添加商品
    add() {
      // 预验证整个表单时候都已经完成
      this.$refs.addFormRef.validate(async vali => {
        if(!vali) {
          return this.$message.error('请输入相关内容')
        }
        // 克隆 addForm 进行数据转换
        const form = _.cloneDeep(this.addForm)
        // 对 goods_cat 处理
        form.goods_cat = form.goods_cat.join(',')
        // 对数组中添加 attrs
        // 对动态参数处理
        this.manyDataList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyDataList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        // 发请求添加商品
        let {data: res} = await this.$http.post('goods',form)
        if(res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        // 路由跳转回 goods 页面
        this.$router.push('/goods')

      })
    }
  },
  computed: {
    cateId() {
      return this.addForm.goods_cat[2];
    },
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}

</style>